import React, { useEffect, useState } from 'react'
import styles from './nav.module.scss'
import { useNavigate, useLocation } from 'react-router-dom'
import { Flex, Dropdown, message, Badge, Drawer } from 'antd'
import classNames from 'classnames'
import { targetUrl } from '@/utils/config'
import { useSelector, useDispatch } from 'react-redux'
import type { MenuProps } from 'antd'
import { createFromIconfontCN } from '@ant-design/icons'
import { message as getMessage } from '@/api/user'
import { socketUrl } from '@/utils/config'
import Chat from '@/components/chat/chat'

import logoPath from '@/assets/img/gg-exam-logo.png'
// import aiPath from '@/assets/img/aiChat.png'
import { GotoPage } from '@/utils/gotoPage'
import { ErrorTip } from '@/utils/errorTip'

const IconFont = createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/c/font_4426980_1yswwpwinhm.js'
})

const Nav: React.FC = () => {
  /**
   * 变量集合
   */
  const navigateTo = useNavigate()
  const { token, userInfo } = useSelector((state: RootState) => state.handleUser)
  const dispatch = useDispatch()
  const [messageApi, contextHolder] = message.useMessage() //消息提示框
  const gotoPage = new GotoPage()
  const location = useLocation()
  const urlIndex = location.pathname.indexOf('/')
  const [userMessage, setUserMessage] = useState<userMessageType[]>()
  const [open, setOpen] = useState(false)
  const [isShowChat, setIsShowChat] = useState(false)
  /**
   * 获取消息
   */
  const GetMessage = async () => {
    const res = await getMessage({}, userInfo.id)
    if (ErrorTip(res)) return messageApi.open({ type: 'error', content: '错误：' + res.message })
    setUserMessage(res.data)
  }
  useEffect(() => {
    GetMessage()
    // const socket = new WebSocket('wss://www.ggxiaoq.cn:8666')
    const socket = new WebSocket(socketUrl)

    socket.addEventListener('message', event => {
      const message = JSON.parse(event.data)
      if (message.type === 'reservation') {
        console.log('考试预约成功:', message.data)
        GetMessage()
      }
    })
  }, [])

  const onClose = () => {
    setOpen(false)
  }

  /**
   * 退出登陆
   */
  const backLogin = () => {
    dispatch({ type: 'setToken', val: '' })
    dispatch({ type: 'setUserInfo', val: {} })
    messageApi.open({
      type: 'success',
      content: '退出成功'
    })
  }

  /**
   * 下拉框 列表
   */
  const items: MenuProps['items'] = [
    {
      key: '1',
      label: (
        //gotoPage.gotoEdit({ from: location.pathname.substring(urlIndex + 1)
        <a
          target="_blank"
          rel="noopener noreferrer"
          onClick={() => {
            messageApi.open({
              type: 'warning',
              content: '开发中'
            })
          }}
        >
          个人中心
        </a>
      )
    },
    {
      key: '2',
      label: (
        <a target="_blank" rel="noopener noreferrer" onClick={() => gotoPage.gotoEdit({ from: location.pathname.substring(urlIndex + 1) })}>
          编辑资料
        </a>
      )
    },
    {
      key: '3',
      label: (
        <a target="_blank" rel="noopener noreferrer" onClick={backLogin}>
          退出登陆
        </a>
      )
    }
  ]

  /**
   * 路由跳转 两个
   */
  function login() {
    navigateTo('/login', { state: { from: 'home' } })
  }
  const register = () => {
    navigateTo('/register', { state: { from: 'home' } })
  }
  //
  const openChat = () => {
    if (!token)
      return messageApi.open({
        type: 'info',
        content: '请先登陆'
      })
    setIsShowChat(true)
  }
  // 关闭聊天
  const closeChat = (msg: boolean | ((prevState: boolean) => boolean)) => {
    setIsShowChat(msg)
  }
  return (
    <>
      {isShowChat && <Chat onClose={closeChat} />}
      {contextHolder}
      <Drawer title="用户消息" onClose={onClose} open={open}>
        {userMessage &&
          userMessage.map((item, index) => (
            <div key={index} style={{ padding: '20px 0' }}>
              <div style={{ borderBottom: '1px solid #000' }}>
                <Flex align="center" justify="space-between">
                  <div>{item.title}</div>
                  <div>{item.createtime}</div>
                </Flex>
              </div>
              <div>{item.content}</div>
            </div>
          ))}
      </Drawer>
      <div className={styles.box_nav}>
        <div className={styles.left}>
          <div className={classNames(styles['box-logo'])} onClick={() => navigateTo('/home', { state: { from: 'home' } })}>
            <Flex vertical={false} align="center">
              <img src={logoPath} alt="" className={classNames(styles.logo)} />
              <div className="title">GG题库</div>
            </Flex>
          </div>
        </div>
        <div className={styles.right}>
          <div className={classNames(styles.box_ai)} onClick={openChat}>
            {/* <Flex align="center">
              <img src={aiPath} alt="" />
              <p>不懂来这里问</p>
            </Flex> */}
          </div>
          {!token && (
            <Flex vertical={false} align="center">
              <div className={[styles.login, styles.btn].join(' ')} onClick={login}>
                登陆
              </div>
              |
              <div className={[styles.register, styles.btn].join(' ')} onClick={register}>
                注册
              </div>
            </Flex>
          )}
          {token && (
            <div className={classNames(styles.have_user)}>
              <Flex align="center" gap={25}>
                {userMessage && (
                  <div onClick={() => setOpen(true)}>
                    <Badge count={userMessage.length}>
                      <IconFont type="icon-xiaoxi" style={{ fontSize: '1.56rem' }} />
                    </Badge>
                  </div>
                )}
                <Dropdown menu={{ items }} placement="bottomLeft" arrow>
                  <div className={classNames(styles.box_userInfo)}>
                    <Flex vertical={false} align="center">
                      <img src={targetUrl + `/${userInfo.avatar}`} alt="" className={classNames(styles.avatar)} />
                      <div className={classNames(styles.user_namae)}>{userInfo.name}</div>
                    </Flex>
                  </div>
                </Dropdown>
              </Flex>
            </div>
          )}
        </div>
      </div>
    </>
  )
}

export default Nav
